package com.css.fxfzypg.modules.baseData.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.common.utils.CheckObjFields;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.dto.PeoDTO;
import com.css.fxfzypg.modules.baseData.queryParams.PeoQueryParams;
import com.css.fxfzypg.modules.baseData.repository.PeoRepository;

import com.css.fxfzypg.modules.baseData.entity.PeoEntity;
import com.css.fxfzypg.modules.baseData.service.PeoService;
import com.css.fxfzypg.modules.baseData.vo.PeoVO;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author y1fan
 * @create 2022-08-11 14:53
 */
@Slf4j
@Service
public class PeoServiceImpl implements PeoService {

    @Resource
    private PeoRepository peoRepository;

    @Autowired
    private SysAreaService sysAreaService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public PeoEntity findPeoById(String dataPeoId) {
        return peoRepository.findPeoById(dataPeoId);
    }


    public void updatePeo(PeoDTO peoDTO) {
        peoDTO.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        peoDTO.setUpdateUser(PlatformSessionContext.getUserID());
        peoRepository.updatePeo(peoDTO);
    }

    @Override
    public Map<String, Object> getAllPeoByParams(PeoQueryParams queryParams, int curPage, int pageSize) {
        Map<String, Object> page = peoRepository.getAllPeoByParams(queryParams, curPage, pageSize);
        return page;
    }

    @Override
    public void deletePeo(List<String> list) {
        peoRepository.deletePeo(list);
    }

    @Override
    public String importExcel(MultipartFile file) {
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setTitleRows(0);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<PeoVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), PeoVO.class, params);

            List<PeoVO> list = result.getList();
            if (PlatformObjectUtils.isNotEmpty(list)) {
                for (PeoVO item : list) {
                    PeoEntity peoEntity = peoRepository.findPeoByProAndCityAndPre(item.getProvince(), item.getCity(), item.getPrefecture());
                    if (PlatformObjectUtils.isNotEmpty(peoEntity)) {
                        BeanUtils.copyProperties(item, peoEntity);
                        peoEntity.setUpdateUser(PlatformSessionContext.getUserID());
                        peoEntity.setUpdateTime(new Date());
                        peoRepository.importExcel(peoEntity);
                    } else {
                        PeoEntity peoEntity1 = new PeoEntity();
                        BeanUtils.copyProperties(item, peoEntity1);
                        String divisionIds = "";
                        try {
                            //判断省市县的名称是否符合规范
                            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(item.getProvince(), "utf-8"),
                                    URLEncoder.encode(item.getCity(), "utf-8"),
                                    URLEncoder.encode(item.getPrefecture(), "utf-8"));
                        } catch (Exception e) {

                        }
                        if (StringUtils.isBlank(divisionIds) || divisionIds.split("_").length < 3) {
                            return "导入失败，请检查" + item.getProvince() + "," + item.getCity() + "," + item.getPrefecture() + "数据正确性";
                        }
                        String[] split = divisionIds.split("_");
                        peoEntity1.setProvinceId(split[0]);
                        peoEntity1.setCityId(split[1]);
                        peoEntity1.setPrefectureId(split[2]);
                        peoEntity1.setIsDelete(YNEnum.N.toString());
                        peoEntity1.setCreateUser(PlatformSessionContext.getUserID());
                        peoEntity1.setCreateTime(new Date());
                        peoEntity1.setDataPeoId(UUIDGenerator.getUUID());
                        peoEntity1.setProvinceCode(areaIdCodeMap.get(peoEntity1.getProvinceId()));
                        peoEntity1.setCityCode(areaIdCodeMap.get(peoEntity1.getCityId()));
                        peoEntity1.setPrefectureCode(areaIdCodeMap.get(peoEntity1.getPrefectureId()));
                        peoRepository.save(peoEntity1);
                    }
                }
            }
            returnMsg.append("成功导入" + (result.getList().size()) + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<PeoVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    PeoVO peoVO = iterator.next();
                    PeoEntity peoEntity2 = new PeoEntity();
                    BeanUtils.copyProperties(peoVO, peoEntity2);
                    if (CheckObjFields.isAllFieldNull(peoEntity2)) {
                        continue;
                    }
                    returnMsg.append("第" + peoVO.getRowNum() + "行 " + peoVO.getErrorMsg() + "<br/>");
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public Integer countByCounty(String province, String city, String county) {
        return peoRepository.countByCounty(province, city, county);
    }

    @Override
    public Integer countByCity(String province, String city) {
        return peoRepository.countByCity(province, city);
    }

    @Override
    public Integer countByProvince(String name) {
        return peoRepository.countByProvince(name);
    }

    @Override
    public Integer countByProvinceAndYear(String provinceName, String taskYear) {
        return peoRepository.countByProvinceAndYear(provinceName, taskYear);
    }
}
